package org.jeecg.modules.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.jeecg.cmbCloudDirectLink.utils.CMBApi;
import org.jeecg.common.api.dto.BankSetDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.manage.entity.CaishuiInternalTransfer;
import org.jeecg.modules.manage.entity.CaishuiRefundRecord;
import org.jeecg.modules.manage.mapper.MCaishuiRefundRecordMapper;
import org.jeecg.modules.manage.service.IMCaishuiCompanySetService;
import org.jeecg.modules.manage.service.IMCaishuiInternalTransferService;
import org.jeecg.modules.manage.service.IMCaishuiRefundRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;


/**
 * @Description: 退款记录
 * @Author: yfkj
 * @Date:   2023-04-10
 * @Version: V1.0
 */
@Service
public class MCaishuiRefundRecordServiceImpl extends ServiceImpl<MCaishuiRefundRecordMapper, CaishuiRefundRecord> implements IMCaishuiRefundRecordService {

    @Autowired
    private IMCaishuiCompanySetService iMCaishuiCompanySetService;
    @Autowired
    private IMCaishuiInternalTransferService iMCaishuiInternalTransferService;


    /**
     * 查询退款总额
     * @param params
     * @return
     */
    @Override
    public Map<String, Object> queryRefundTotal(Map<String, String> params) {
        return this.baseMapper.queryRefundTotal(params);
    }

    /**
     * 企银支付业务查询
     * @param yurRef
     * @return
     */
    @Override
    @Transactional
    public Result<?> queryRefundResult(String yurRef) {
        CaishuiRefundRecord refundRecord = baseMapper.selectOne(new LambdaQueryWrapper<CaishuiRefundRecord>().eq(CaishuiRefundRecord::getYurRef,yurRef));
        if (oConvertUtils.isEmpty(refundRecord)) return Result.error("退款信息不存在！");
        //企银支付业务查询
        BankSetDTO bankSetDTO = iMCaishuiCompanySetService.queryCompanySet(refundRecord.getPayAccount());
        Result result = CMBApi.queryPaymentSingle(yurRef, bankSetDTO);
        if (result.isSuccess()){
            if (oConvertUtils.isEmpty(result.getResult())) return Result.error("暂无查询结果！");
            JsonArray jsonArray = new GsonBuilder().create().fromJson(result.getResult().toString(), JsonArray.class);
            JsonObject jsonObject = jsonArray.get(0).getAsJsonObject();
            if (oConvertUtils.isEmpty(jsonObject)) return Result.error("暂无查询结果！");
            String reqSts = oConvertUtils.isEmpty(jsonObject.get("reqSts")) ? "" : jsonObject.get("reqSts").getAsString();
            String rtnFlg = oConvertUtils.isEmpty(jsonObject.get("rtnFlg")) ? "" : jsonObject.get("rtnFlg").getAsString();
            String rtnNar = oConvertUtils.isEmpty(jsonObject.get("rtnNar")) ? "" : jsonObject.get("rtnNar").getAsString();
            if ("FIN".equals(reqSts)){//银行已处理完成
                if ("S".equals(rtnFlg)) { //银行支付成功
                    if (refundRecord.getStatus()!=4) {
                        refundRecord.setReqSts(reqSts);
                        refundRecord.setRtnFlg(rtnFlg);
                        refundRecord.setStatus(4);
                        refundRecord.setFinishTime(new Date());

                        /**记账子单元内部转账：服务费转入账号对应的默认子账户（招商银行银企直联会有一个默认子账户000000）*/
                        if (refundRecord.getServiceFee() > 0) {
                            Result zz_result = CMBApi.doInternalTransfer(refundRecord.getPayAccount(),refundRecord.getPayDmanbr(),
                                    "000000",refundRecord.getServiceFee().toString(),"退款服务费", bankSetDTO);
                            if(zz_result.isSuccess()){
                                //新增记账子单元内部转账记录
                                JsonArray ntdmatrxz1 = new GsonBuilder().create().fromJson(zz_result.getResult().toString(), JsonArray.class);
                                for (JsonElement jsonElement : ntdmatrxz1) {
                                    CaishuiInternalTransfer internalTransfer = new CaishuiInternalTransfer();
                                    internalTransfer.setCompanyId(refundRecord.getCompanyId());
                                    internalTransfer.setBusinessId(refundRecord.getBusinessId());
                                    internalTransfer.setTenantId(refundRecord.getTenantId());
                                    internalTransfer.setOrderNo(refundRecord.getYurRef());
                                    internalTransfer.setTrxdat(jsonElement.getAsJsonObject().get("trxdat").getAsString());
                                    internalTransfer.setAccnbr(jsonElement.getAsJsonObject().get("accnbr").getAsString());
                                    internalTransfer.setDmanbr(jsonElement.getAsJsonObject().get("dmanbr").getAsString());
                                    internalTransfer.setTrxnbr(jsonElement.getAsJsonObject().get("trxnbr").getAsString());
                                    internalTransfer.setTrxamt(jsonElement.getAsJsonObject().get("trxamt").getAsString());
                                    internalTransfer.setTrxdir(jsonElement.getAsJsonObject().get("trxdir").getAsString());
                                    iMCaishuiInternalTransferService.save(internalTransfer);
                                }
                            }else {
                                refundRecord.setStatus(6);//记账子单元内部转账失败
                                log.error("【"+refundRecord.getYurRef()+"】记账子单元内部转账失败[退款服务费]：" + zz_result.getMessage());
                            }
                        }
                        baseMapper.updateById(refundRecord);
                    }
                    return Result.ok("银行处理完成，支付成功!");
                } else {
                    refundRecord.setReqSts(reqSts);
                    refundRecord.setRtnFlg(rtnFlg);
                    refundRecord.setFailReason(rtnNar);
                    refundRecord.setStatus(5);
                    refundRecord.setFinishTime(new Date());
                    baseMapper.updateById(refundRecord);
                    return Result.error("银行处理完成，支付失败!");
                }
            } else {
                return Result.ok("银行处理中，请耐心等待！");
            }
        } else {
            return Result.error(result.getMessage());
        }
    }

}
